﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
using Galaktika.BI.Silverlight.Controls.MemberChoice.Info;
using Galaktika.BI.Silverlight.Controls.General.Tree;

namespace Galaktika.BI.Silverlight.Controls.MemberChoice.Tree
{
    public class MemberTreeNode : TreeViewItem
    {
        OlapMemberInfo m_MemberInfo = null;
        public OlapMemberInfo MemberInfo
        {
            get {
                return m_MemberInfo;
            }
        }

        public MemberTreeNode(OlapMemberInfo info, bool useMultiSelect)
        {
            if (info == null)
                throw new ArgumentNullException("info");

            TreeItemControl item_ctrl = new TreeItemControl(useMultiSelect);
            item_ctrl.Text = info.Text;
            // В случае множ. выбора клик на иконке используем для изменения состояния
            item_ctrl.IconClick += new EventHandler(item_ctrl_IconClick);
            Header = item_ctrl;

            m_MemberInfo = info;

            if (useMultiSelect)
            {
                UpdateNodeIcon();
            }

            info.StateChanged += new OlapMemberInfo.StateChangedEventHandler(info_StateChanged);
        }

        void info_StateChanged(OlapMemberInfo sender)
        {
            UpdateNodeIcon();
        }

        void item_ctrl_IconClick(object sender, EventArgs e)
        {
            //Переводим в следующее состояние
            MemberInfo.SetNextState();

            //Генерим событие "Изменилось стоятояние выбранности"
            //Raise_SelectionStateChanged();
        }

        private void UpdateNodeIcon()
        {
            TreeItemControl item_ctrl = Header as TreeItemControl;
            if (item_ctrl != null)
            {
                item_ctrl.Icon = MemberChoiceControl.GetIconImage(MemberInfo);
            }
        }

        public bool IsWaiting
        {
            set
            {
                TreeViewItem waitItem = GetSpecialNode(SpecialNodes.Wait);
                if (!value)
                {
                    if (waitItem != null)
                    {
                        
                        Items.Remove(waitItem);
                    }
                }
                else
                {
                    if (waitItem == null)
                        AddSpecialNode(SpecialNodes.Wait);
                }
            }
            get
            {
                if (GetSpecialNode(SpecialNodes.Wait) != null)
                    return true;
                else
                    return false;
            }
        }

        public bool IsFullLoaded
        {
            set
            {
                TreeViewItem nextItem = GetSpecialNode(SpecialNodes.LoadNext);
                TreeViewItem allItem = GetSpecialNode(SpecialNodes.LoadAll);
                if (value)
                {
                    if (nextItem != null)
                    {
                        nextItem.Expanded -= new RoutedEventHandler(node_Expanded);
                        Items.Remove(nextItem);
                    }
                    if (allItem != null)
                    {
                        allItem.Expanded -= new RoutedEventHandler(node_Expanded);
                        Items.Remove(allItem);
                    }
                }
                else
                {
                    if (nextItem == null)
                        AddSpecialNode(SpecialNodes.LoadNext);
                    if (allItem == null)
                        AddSpecialNode(SpecialNodes.LoadAll);
                }
            }
            get
            {
                if (GetSpecialNode(SpecialNodes.LoadNext) == null &&
                    GetSpecialNode(SpecialNodes.LoadAll) == null)
                    return true;
                else
                    return false;
            }
        }

        /// <summary>
        /// Проверяет загружались ли дочерние узлы. 
        /// </summary>
        public bool IsInitialized
        {
            get
            {
                //Если у элемента один дочерний и он "WaitNode", то значит данные не грузились
                if (Items.Count == 1 && IsWaiting)
                {
                    return false;
                }
                return true;
            }
        }

        private enum SpecialNodes
        { 
            Wait,
            LoadNext,
            LoadAll
        }

        private TreeViewItem AddSpecialNode(SpecialNodes nodeType)
        {
            TreeViewItem node = null;
            switch (nodeType)
            { 
                case SpecialNodes.Wait:
                    node = new WaitTreeNode();
                    break;
                case SpecialNodes.LoadNext:
                    node = new LoadNextTreeNode();
                    node.Expanded += new RoutedEventHandler(node_Expanded);
                    break;
                case SpecialNodes.LoadAll:
                    node = new LoadAllTreeNode();
                    node.Expanded += new RoutedEventHandler(node_Expanded);
                    break;
            }
            if (node != null)
            {
                Items.Add(node);
            }
            return node;
        }

        public event EventHandler SpecialNodeExpanded;

        void node_Expanded(object sender, RoutedEventArgs e)
        {
            EventHandler handler = this.SpecialNodeExpanded;
            if (handler != null)
            {
                handler(sender, EventArgs.Empty);
            }
        }

        TreeViewItem GetSpecialNode(SpecialNodes nodeType)
        {
            foreach (object obj in Items)
            {
                switch (nodeType)
                {
                    case SpecialNodes.Wait:
                        WaitTreeNode wait = obj as WaitTreeNode;
                        if (wait != null)
                            return wait;
                        break;
                    case SpecialNodes.LoadNext:
                        LoadNextTreeNode next = obj as LoadNextTreeNode;
                        if (next != null)
                            return next;
                        break;
                    case SpecialNodes.LoadAll:
                        LoadAllTreeNode all = obj as LoadAllTreeNode;
                        if (all != null)
                            return all;
                        break;
                }
            }
            return null;
        }


    }
}
